package leetcode.l0613;

/**
 * @author Retain
 * @date 2021/6/13 17:53
 */
public class Medium_不同路径2_63 {

    public static void main(String[] args) {
        uniquePathsWithObstacles(new int[][]{{0,0,0},{0,1,0},{0,0,0}});
    }
    /**
     * 上一题的升级版，增加了障碍物，更像迷宫问题了。
     * dp[i][j] = dp[i-1][j]+ dp[i][j-1]，遇到障碍物将其置为0;
     * 这道题的边界条件很多，需要慢慢考虑
     * @param obstacleGrid
     * @return
     */
    public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        // 入口放障碍物
        if (obstacleGrid[0][0] == 1) {
            return 0;
        }
        // 数组长度小于等于1
        if (obstacleGrid.length <= 1 ) {
            if (obstacleGrid[m-1][n-1] == 1) {
                return 0;
            }
            return 1;
        }

        int[][] dp = new int[m][n];
        //初始化dp[][]
        dp[0][0] = 1;
        for (int i = 1; i < n; i++) {
            // 第一排遇到障碍物后面都不可达
            if (obstacleGrid[0][i] == 1) {
                break;
            }
            dp[0][i] = 1;
        }
        // 第一列遇到障碍物后面都不可达
        for (int i = 1; i < m; i++) {
            if (obstacleGrid[i][0] == 1) {
                break;
            }
            dp[i][0] = 1;
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] == 1) {
                    dp[i][j] = 0;
                }else {
                    dp[i][j] = dp[i-1][j]+dp[i][j-1];
                }
            }
        }
        return dp[m-1][n-1];
    }
}
